using Microsoft.Office.Server.Search.Administration;
using Microsoft.SharePoint;
using Winsmarts.SSPC.Common;
using Winsmarts.SSPC.ManagedProperties.BO;

namespace Winsmarts.SSPC.ManagedProperties
{
    public static class HelperClass
    {
        public const string XmlNodeName = "ManagedProperties";

        public static void ExportXML(ProgramInputs inputs)
        {
            Schema schema = new Schema(SearchContext.GetContext(new SPSite(inputs.SSPURL)));

            Serializer propertyCollection = new Serializer();
            foreach (ManagedProperty theProperty in schema.AllManagedProperties)
            {
                propertyCollection.AddItem(XmlNodeName, new ManagedPropertyInfo(theProperty));
            }

            propertyCollection.Save(inputs.FileName);
        }


        public static void ImportXML(ProgramInputs inputs)
        {
            Serializer workingData = new Serializer();
            workingData.Load( inputs.FileName );

            Schema schema = new Schema(SearchContext.GetContext(new SPSite(inputs.SSPURL)));

            foreach (ManagedPropertyInfo inputManagedProperty in workingData.GetItems(XmlNodeName, typeof(ManagedPropertyInfo)))
            {
                ManagedProperty managedProperty;

                if (schema.AllManagedProperties.Contains(inputManagedProperty.Name))
                {
                    // Get the existing Managed Property
                    managedProperty = schema.AllManagedProperties[inputManagedProperty.Name];

                    Trace.WriteLine("Updating managed property:" + inputManagedProperty.Name);
                }
                else
                {
                    // Add the Datatype handler
                    managedProperty = schema.AllManagedProperties.Create(
                        inputManagedProperty.Name,
                        inputManagedProperty.GetManagedDataType());

                    Trace.WriteLine("Adding managed property:" + inputManagedProperty.Name);
                }

                inputManagedProperty.SetManagedProperties(managedProperty, schema, inputs.RemoveExcessMappings);

            }
        }


    }
}